#include<iostream>
#include<pthread.h>
#include<unistd.h>
#include<ctime>
#include"RingQueue.hpp"

using namespace std;

pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;

void* Productor(void* args)
{
    pthread_detach(pthread_self());
    RingQueue<int>* bq=static_cast<RingQueue<int>*>(args);

    while(true)
    {
        //生产数据
        int data=rand()%10+1;

        //添加数据
        bq->push(data);
        pthread_mutex_lock(&mutex);
        cout<<"The productor of ID:"<<pthread_self()<<" create a data,data is: "<<data<<endl;
        pthread_mutex_unlock(&mutex);

        usleep(1000*10);
    }
}

void* Consumer(void* args)
{
    pthread_detach(pthread_self());
    RingQueue<int>* bq=static_cast<RingQueue<int>*>(args);

    while(true)
    {  
        //消费数据
        int data;
        bq->pop(&data);
        pthread_mutex_lock(&mutex);
        cout<<"The Consumer of ID:"<<pthread_self()<<"get a data,data is:"<<data<<endl;
        pthread_mutex_unlock(&mutex);
        //处理数据
        //TODO
        usleep(1000*10);
    }
}

int main()
{
    srand(time(nullptr));

    RingQueue<int>* bq=new RingQueue<int>();

    pthread_t p[5],c[3];
    for(int i=0;i<5;i++)
    {
        pthread_create(p+i,nullptr,Productor,bq);
    }
    for(int i=0;i<3;i++)
    {
        pthread_create(c+i,nullptr,Consumer,bq);
    }

    // pthread_join(p,nullptr);
    // pthread_join(c,nullptr);
    while(1)sleep(1);//不能让主线程先噶了

    return 0;
}